import pytest
from unittest.mock import MagicMock


# 模拟的API响应基类
class MockResponse:
    def __init__(self, status_code, json_data):
        self.status_code = status_code
        self.json_data = json_data

    def json(self):
        return self.json_data


# 测试客户端模拟类
class TestClient:
    def __init__(self):
        self.responses = {}

    def register_response(self, url, response):
        self.responses[url] = response

    def send_request(self, method, url, params):
        # 模拟请求路由匹配
        key = f"{method}://{url}"
        if key in self.responses:
            return self.responses[key]
        else:
            return MockResponse(404, {"error": "Not Found"})


# 测试夹具 - 创建模拟客户端
@pytest.fixture
def client():
    return TestClient()


# 正常用例：正确参数返回实例状态
def test_describe_instances_success(client):
    expected_response = {
        "TotalCount": 2,
        "InstanceStatusSet": [
            {"InstanceId": "ins-123", "InstanceState": "RUNNING"},
            {"InstanceId": "ins-456", "InstanceState": "STOPPED"}
        ],
        "RequestId": "req-123"
    }

    client.register_response(
        "GET://cvm.tencentcloudapi.com/",
        MockResponse(200, expected_response)
    )

    # 这里替换为实际的API调用代码（需用户自行实现）
    # response = your_api_client.describe_instances(...)
    # assert response == expected_response


# 错误码测试用例
@pytest.mark.parametrize("error_code, error_msg", [
    ("InvalidInstanceId.Malformed", "实例ID格式错误"),
    ("InvalidParameterValue.LimitExceeded", "Limit参数超出限制"),
    ("InvalidParameterValue.OffsetExceeded", "Offset参数超出范围"),
    ("MissingParameter", "缺少必选参数"),
    ("InternalError", "内部服务错误"),
    ("UnauthorizedOperation", "鉴权失败")
])
def test_error_cases(client, error_code, error_msg):
    error_response = {
        "Response": {
            "Error": {
                "Code": error_code,
                "Message": error_msg
            }
        }
    }

    client.register_response(
        "GET://cvm.tencentcloudapi.com/",
        MockResponse(400, error_response)
    )

    # 这里替换为实际的API调用代码（需用户自行实现）
    # with pytest.raises(Exception) as e:
    #     your_api_client.describe_instances(...)
    # assert str(e.value) == error_msg


# 参数边界测试
def test_limit_max_value(client):
    client.register_response(
        "GET://cvm.tencentcloudapi.com/",
        MockResponse(200, {"TotalCount": 100, "InstanceStatusSet": [{}] * 100})
    )

    # 测试Limit=100的情况
    # assert len(response["InstanceStatusSet"]) == 100


def test_offset_paging(client):
    client.register_response(
        "GET://cvm.tencentcloudapi.com/?Offset=2&Limit=1",
        MockResponse(200, {"TotalCount": 5, "InstanceStatusSet": [{}]}),
        headers={"x-next-offset": "3"}
    )

    # 测试分页功能
    # response = your_api_client.describe_instances(Offset=2, Limit=1)
    # assert response["InstanceStatusSet"][0] == {...}
    # assert response.headers["x-next-offset"] == "3"


# 异常参数类型测试
def test_invalid_parameter_type(client):
    client.register_response(
        "GET://cvm.tencentcloudapi.com/?InstanceIds.0=invalid_id",
        MockResponse(400, {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.InstanceIdMalformed",
                    "Message": "实例ID格式错误"
                }
            }
        })
    )

    # 测试非字符串类型的InstanceIds
    # with pytest.raises(TypeError):
    #     your_api_client.describe_instances(InstanceIds=[123])


# 测试空参数处理
def test_empty_parameters(client):
    client.register_response(
        "GET://cvm.tencentcloudapi.com/",
        MockResponse(200, {"TotalCount": 0, "InstanceStatusSet": []})
    )

    # 测试空InstanceIds的情况
    # response = your_api_client.describe_instances()
    # assert response["TotalCount"] == 0